<template>
  <div class="food-list" v-if="index === 0">
    <van-tree-select
      v-model:main-active-index="activeIndex"
      height="55vw"
      :items="items"
      @click-nav="navClick"
    >
      <template #content>
        <div v-for="(item,index) in subItem" :key="index" class="item-bg">
            <ListItem :item="item" 
            :handleAdd="handleAdd" :handleChange="handleChange"/>
        </div>
    </template>
    </van-tree-select>
  </div>

    <div v-else>{{ foodData.content }}</div>
</template>

<script>
import { reactive, toRefs } from 'vue'
import FoodListItem from './FoodListItem.vue';
import ListItem from '../../../components/ListItem.vue';

export default {
    components:{FoodListItem, ListItem },
    props:['index','foodData'],
    // props:形参
    setup(props){
        let data = reactive({
            activeIndex:0,
            items: [],
            subItem:[]//
        });
        // 初始化数据
         const initData = ()=>{
            let newArray = [];
            props.foodData?.items?.forEach((item,index)=>{
                newArray.push({
                    text:item.text
                });
               if(data.activeIndex === index) {
                 // 最后的subItem 是最后一项
                   data.subItem = item.children //获取subItem
               }
            })
            data.items = newArray //替换
        }

        initData();//调用

        // 获取侧边导航的索引
        const navClick = (i) =>{
            // console.log(i);//侧边导航的索引
            data.activeIndex = i
            initData()
        };
        //handleAdd: 点击加号，出现数量+-
        const handleAdd = (id)=>{
            data.subItem.forEach((item,index)=>{
                if(item.id === id){
                    item.add = false
                    item.num += 1
                }
            })
        }
        //handleChange: 数量+-变化
        const handleChange = (value,detail)=>{
            data.subItem.forEach((item,index)=>{
                if(item.id === detail.name){
                    item.num = value
                }
            });
            // console.log(data.subItem);
        }


        return {
            ...toRefs(data),
            navClick,
            handleAdd, handleChange
        }
    }
}
</script>

<style lang="less" scoped>
  .food-list {
  margin-top: 20px;
  .item-bg {
    padding: 10px;
  }
  }
  /deep/ .van-tree-select__item--active {
    color: #ffc400;
  }
  /deep/ .van-sidebar-item--select::before {
    background-color: #ffc400;
  }
</style>